import csv
import random
import math
import operator

def loadDataset(filename, split, trainingSet=[], testSet=[]):
    """
    对数据进行整理
    :filename: 导入数据集文件名称
    :split: 区分训练集与测试集指标
    :trainingSet: 训练集
    :testSet: 测试集
    """
    with open(filename, 'r') as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        for x in range(len(dataset)-1):
            for y in range(4):
                dataset[x][y] = float(dataset[x][y])
            if random.random() < split:
                trainingSet.append(dataset[x])
            else:
                testSet.append(dataset[x])

def euclideanDistance(instance1, instance2, length):
    """
    算出其k
    :instance1: 表示训练集的点
    :instance2: 表示预测集的点
    :length: 表示维度
    """
    distance = 0
    for x in range(length):
        distance += pow((instance1[x] - instance2[x]), 2)
    return math.sqrt(distance)

def getNeighbors(trainingSet, testInstance, k):
    """
    返回距离测试实例的最近的邻居
    :trainingSet: 数据项
    :testInstance: 一个测试实例
    :k: k个数量训练集距离testInstance的label
    """
    distances = []
    length = len(testInstance) - 1
    for x in range(len(trainingSet)):
        dist = euclideanDistance(testInstance, trainingSet[x], length)
        distances.append((trainingSet[x], dist))
    distances.sort(key=operator.itemgetter(1)) # 获取对象第一个域里的值
    print(distances)
    neighbors = []
    for x in range(k):
        neighbors.append(distances[x][0])
    return neighbors

def getResponse(neighbors):
    """
    统计邻居分类的多少
    :neighbors: 邻居数据
    :return: 邻居分类最多的 
    """
    classVotes = {}
    for x in range(len(neighbors)):
        response = neighbors[x][-1]
        if response in classVotes:
            classVotes[response] += 1
        else:
            classVotes[response] = 1
    sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True) # reverse按降序排列
    return sortedVotes[0][0]

def getAccuracy(testSet, predictions):
    """
    预测算法的精确度
    :testSet: 测试集
    :predictions: 算法算出的结果
    """
    correct = 0
    for x in range(len(testSet)):
        if testSet[x][-1] == predictions[x]:
            correct += 1
    return (correct/float(len(testSet))) * 100.0

def main():
    tariningSet = []
    testSet = []
    split = 0.67
    print(split)
    loadDataset(r'irisdata.txt', split, tariningSet, testSet)
    print('Train set:' + repr(len(tariningSet)))
    print('Train set:' + repr(len(testSet)))
    predictions = []
    k = 3
    for x in range(len(testSet)):
        neighbors = getNeighbors(tariningSet, testSet[x], k)
        result = getResponse(neighbors)
        predictions.append(result)
        # print('> predicted=' + repr(result) + ', actual=')
    accuracy = getAccuracy(testSet, predictions)
    print('Accuracy: ' + repr(accuracy) + '%')

if __name__ == '__main__':
    main()